from django.shortcuts import render,redirect
from django.views import View
from django import http
import re
from .models import User
from django.contrib.auth import login
from meiduo_mall.utils.response_code import RETCODE
from django_redis import get_redis_connection

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):
        username=request.POST.get('user_name')
        password = request.POST.get('pwd')
        password2 = request.POST.get('cpwd')
        mobile = request.POST.get('phone')
        sms_code = request.POST.get('msg_code')
        allow = request.POST.get('allow')

        if not all([username,password,password2,mobile,sms_code,allow]):
            return http.HttpResponseForbidden('填写数据不完整')
        if not re.match('^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden('用户名格式错误')
        if User.objects.filter(username = username).count()>0:
            return http.HttpResponseForbidden('用户名已存在')
        if not re.match('^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden('密码为8到20个字符')
        if password!=password2:
            return http.HttpResponseForbidden('两个密码不一致')
        if not re.match('^1[345789]\d{9}$',mobile):
            return http.HttpResponseForbidden('手机号错误')
        if User.objects.filter(mobile=mobile).count()>0:
            return http.HttpResponseForbidden('手机号存在')

        redis_cli = get_redis_connection('sms_code')
        sms_code_redis = redis_cli.get(mobile)
        if sms_code_redis is None:
            return http.HttpResponseForbidden('短信验证码已过期')
        redis_cli.delete(mobile)
        redis_cli.delete(mobile+'_flag')
        if sms_code_redis.decode() != sms_code:
            return http.HttpResponseForbidden('短信验证码错误')

        user=User.objects.create_user(
            username=username,
            password=password,
            mobile=mobile
         )

        login(request,user)

        return redirect('/')


class UsernameCountView(View):
    def get(self, request,username):
        count = User.objects.filter(username=username).count()

        return http.JsonResponse({
            'count':count,
            'code':RETCODE.OK,
            'errmsg':'OK'
        })
class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({
            'count': count,
            'code': RETCODE.OK,
            'errmsg': 'OK'
        })